package com.apes.fn.scm.internal.help.service;

import com.apes.fn.scm.internal.help.model.InternalHelpReturnApproval;
import com.apes.fn.scm.internal.help.model.InternalHelpReturnApprovalItem;
import com.apes.fn.scm.internal.help.service.voucher.ReturnAccountService;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.scm.sal.saleOrder.SaleOrderItem;
import com.apes.scm.sal.saleOrder.SaleOrderItemRepository;
import com.apes.scm.voucher.model.VoucherItem;
import com.apes.scm.voucher.repository.VoucherItemRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 内协分销退回服务
 *
 * @Author wuq
 * @Date 2021-11-4
 */
@Service
public class InternalHelpSaleOrderReturnService extends DomainService {

    @Autowired
    private VoucherItemRepository voucherItemRepository;
    @Autowired
    private ReturnAccountService returnAccountService;

    public void process(SimpleRequest request) {
        InternalHelpReturnApproval internalHelpReturnApproval = request.getO(InternalHelpReturnApproval.class);

        // 根据内协退货明细找出对应的分销单明细行（可能存在部分退货）
        HashMap<SaleOrderItem, InternalHelpReturnApprovalItem> map = new HashMap();     // 构造出退货明细对应的分销单明细
        internalHelpReturnApproval.getApprovalItems().forEach(returnItem -> map.put(getSaleOrderItem(returnItem), returnItem));

        // 根据分销单明细区分出退货类型
        List<SaleOrderItem> saleOrderItems = map.entrySet().stream().map(Map.Entry::getKey).collect(Collectors.toList());
        saleOrderItems.stream().collect(Collectors.groupingBy(SaleOrderItem::getProductRule))
                .forEach((productRule, orderItems) -> {

                    // 构造对应的退货明细
                    HashMap<SaleOrderItem, InternalHelpReturnApprovalItem> itemHashMap = new HashMap();
                    orderItems.forEach(item -> itemHashMap.put(item, map.get(item)));

                    if (productRule == 10) {         // 代销带安
                        returnAccountService.returnSaleOutHelp(itemHashMap);
                    }

                    if (productRule == 20) {         // 经销带安
                        returnAccountService.returnSalePlanOutHelp(itemHashMap);
                    }

                    if (productRule == 30) {        // 区分服务商品、油漆商品
                        orderItems.stream().collect(Collectors.groupingBy(SaleOrderItem::isPaintFlag))
                                .forEach((isPaint, serviceItems) -> {
                                    HashMap<SaleOrderItem, InternalHelpReturnApprovalItem> autMap = new HashMap();
                                    if (isPaint) {
                                        // 油漆部分
                                        serviceItems.forEach(item -> autMap.put(item, map.get(item)));
                                        returnAccountService.returnSalePaint(autMap);
                                    } else {
                                        // 服务商品部分
                                        serviceItems.forEach(item -> autMap.put(item, map.get(item)));
                                        returnAccountService.returnSaleAut(autMap);
                                    }
                                });
                    }
                });

    }

    private SaleOrderItem getSaleOrderItem(InternalHelpReturnApprovalItem internalHelpReturnApprovalItem) {
        // 通过商品库存价值 找采购凭证
        VoucherItem vItem = voucherItemRepository.findOne(internalHelpReturnApprovalItem.getInventoryBatch().getBatchNumber());
        Optional.ofNullable(vItem.getSupplierRef()).orElseThrow(() -> new RuntimeException("通过商品库存价值未找到记录有內协销售的采购凭证" + internalHelpReturnApprovalItem.getInventoryBatch().getId()));

        // 服务方案采购凭证上面的 supplierRef 就是分销单的明细行号
        SaleOrderItem saleOrderItem = SpringManager.getBean(SaleOrderItemRepository.class).findOne(vItem.getSupplierRef());
        Optional.ofNullable(saleOrderItem).orElseThrow(() -> new RuntimeException("获取分销单失败！采购入库凭证" + vItem.getVoucher().getId() + "约定好的参考字段(分销明细)为" + vItem.getSupplierRef()));
        return saleOrderItem;
    }
}
